package com.hqd.ch03.v24.utils;

import com.hqd.ch03.v24.tx.transaction.support.TransactionSynchronizationManager;
import com.hqd.ch03.v26.jdbc.datasource.ConnectionHolder;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public abstract class DataSourceUtils {
    public static Connection getConnection(DataSource dataSource) throws SQLException {
        return doGetConnection(dataSource);
    }

    private static Connection doGetConnection(DataSource dataSource) throws SQLException {
        Object resource = TransactionSynchronizationManager.getResource(dataSource);
        if (resource instanceof Connection) {
            return (Connection) resource;
        } else if (resource instanceof ConnectionHolder) {
            return ((ConnectionHolder) resource).getConnection();
        }
        return null;
    }
}
